<template>
	<view>
		<view class="goods-item">
			<!-- 左边区域 -->
			<view class="goods-left">
				<!-- 单选按钮区域 -->
				<radio :checked="goods.goods_state" color="#d81e06" value="" v-if="showRadio" @click="changeRadio" />
				<!-- 图片区域 -->
				<image :src="goods.goods_small_logo || defaultPic"></image>
			</view>
			<!-- 右边区域 -->
			<view class="goods-right">
				<!-- 标题区域 -->
				<view class="goods-title">{{ goods.goods_name }}</view>
				<view class="goods-info">
					<!-- 价格区域 -->
					<view class="goods-price">￥{{ goods.goods_price | formatPrice }}</view>
					<!-- 数字输入框区域 -->
					<uni-number-box :min="0" :value="goods.goods_count" v-if="showNum" @change="changeNum"></uni-number-box>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'my-goods',
	props: {
		// 检测类型 + 其他验证
		goods: {
			type: Object,
			default: () => ({})
		},
		// 是否显示单选按钮？
		showRadio: {
			type: Boolean,
			default: false
		},
		// 是否显示数字数入框？
		showNum: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			// 默认图片
			defaultPic: 'https://img1.baidu.com/it/u=117938972,521936855&fm=253&fmt=auto&app=138&f=JPEG?w=1201&h=500'
		};
	},
	methods: {
		// 切换单选按钮
		changeRadio() {
			// 自定义事件 命名为:change-radio、父组件使用:@change-radio=""
			this.$emit('change-radio', {
				goods_id: this.goods.goods_id,
				goods_state: !this.goods.goods_state
			});
		},
		// 切换数量
		changeNum(val) {
			// 正则校验 只接收正整数
			const regex = /^([1-9]\d*)$/;
			let newVal = 0;
			if (regex.test(val)) {
				newVal = val;
			} else {
				newVal = 1;
			}
			// 自定义事件 命名为:change-num、父组件使用:@change-num=""
			this.$emit('change-num', {
				goods_id: this.goods.goods_id,
				goods_count: newVal
			});
		}
	},
	filters: {
		// 格式化价格
		formatPrice(price) {
			return Number(price).toFixed(2);
		}
	}
};
</script>

<style lang="scss">
// 商品列表项
.goods-item {
	display: flex;
	padding: 0 5px;
	border-bottom: 5px solid #efefef;
	// 左边区域
	.goods-left {
		margin-right: 5px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		image {
			height: 100px;
			width: 100px;
			display: block;
		}
	}
	// 右边区域
	.goods-right {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		flex: 1;
		.goods-title {
			font-size: 13px;
			text-align: justify;
		}
		.goods-info {
			display: flex;
			justify-content: space-between;
			color: #d81e06;
			font-size: 16px;
		}
	}
}
</style>
